<template>
  <div>
    <!-- 设备信息表单弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="props.isReadonly ? 800 : 700"
      draggable
      :align-center="true"
      @close="closeDialog"
      style="min-width: 700px"
      destroy-on-close
      class="maxhDialog"
    >
      <el-descriptions :column="2" size="large" border v-if="props.isReadonly">
        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">设备编号</div>
          </template>
          {{ formData.equipCode || "" }}
        </el-descriptions-item>
        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">设备名称</div>
          </template>
          {{ formData.equipName || "" }}
          <el-tag v-if="formData.enabled === 1" type="success" class="ml-2"
            >启用</el-tag
          >
          <el-tag v-else type="info" class="ml-2">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">设备类型</div>
          </template>
          {{ formData.equipCode + "-" + formData.equipTypeCode }}
        </el-descriptions-item>
        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">生产设备</div>
          </template>
          {{ formData.processEquipCode || "" }}
        </el-descriptions-item>
        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">位置</div>
          </template>
          {{ formData.locationName || "" }}
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.imgUrl && formData.imgUrl.length"
          :span="1"
        >
          <template #label>
            <div class="cell-item">图片</div>
          </template>
          <div>
            <UploadImge
              :action="`${actionUrl}/system/fileCenter/uploadFile/${formData.imgUrl}`"
              v-model="formData.imgUrl"
              :domainName="`${actionUrl}`"
              :isReadonly="props.isReadonly"
              :uploadStyle="{ width: '100px', height: '67px' }"
            />
          </div>
        </el-descriptions-item>
        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">连接方式</div>
          </template>
          {{
            dictionaryStore.filterDictName(
              "EquipConnectionMode",
              formData.connectionMode
            ) || ""
          }}
        </el-descriptions-item>

        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">IP地址</div>
          </template>
          {{ formData.ipAddress || "" }}
        </el-descriptions-item>

        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">设备端口</div>
          </template>
          {{ formData.equipPort || "" }}
        </el-descriptions-item>

        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">opc设备</div>
          </template>
          {{ formData.opcDeviceId || "" }}
        </el-descriptions-item>

        <el-descriptions-item :span="1">
          <template #label>
            <div class="cell-item">opc通道</div>
          </template>
          {{ formData.opcChannelId || "" }}
        </el-descriptions-item>

        <el-descriptions-item :span="1" v-if="formData.remarks">
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          {{ formData.remarks || "" }}
        </el-descriptions-item>
      </el-descriptions>
      <el-form
        ref="formRef"
        v-if="!props.isReadonly"
        :model="formData"
        :rules="rules"
        label-width="90"
        style="position: relative"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="equipCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.equipCode"
                placeholder="请输入设备编号"
                clearable
              />
              <span v-else>{{ formData.equipCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.equipName"
                placeholder="请输入设备名称"
                clearable
              />
              <span v-else>{{ formData.equipName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipTypeId">
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.equipTypeId"
                placeholder="请选择设备类型"
                clearable
              >
                <el-option
                  v-for="item in equipTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                formData.equipCode + "-" + formData.equipTypeCode
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="生产设备" prop="processEquipCode">
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.processEquipId"
                placeholder="请选择生产设备"
                clearable
                @change="handleProcessEquip"
              >
                <el-option
                  v-for="item in equipProduceList"
                  :key="item.id"
                  :label="item.equipName"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.processEquipCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12"
        /></el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="位置" prop="locationId">
              <el-tree-select
                v-if="!props.isReadonly"
                placeholder="请输入位置"
                style="width: 300px"
                filterable
                v-model="formData.locationId"
                :data="locationInfoTree"
                node-key="id"
                clearable
                :props="{ label: 'locationName', children: 'nodes' }"
                @node-click="(e:object) => handleLocationChange(e)"
                check-strictly
                :render-after-expand="false"
              />

              <span v-else>{{ formData.locationName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="连接方式" prop="connectionMode">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.connectionMode"
                placeholder="请选择连接方式"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'EquipConnectionMode'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <span v-else>{{
                dictionaryStore.filterDictName(
                  "EquipConnectionMode",
                  formData.connectionMode
                )
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.ipAddress"
                placeholder="请输入IP地址"
                clearable
              />
              <span v-else>{{ formData.ipAddress }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备端口" prop="equipPort">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.equipPort"
                placeholder="请输入设备端口"
                clearable
              />
              <span v-else>{{ formData.equipPort }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="opc设备" prop="opcDeviceId">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.opcDeviceId"
                placeholder="请输入opc设备"
                clearable
              />
              <span v-else>{{ formData.opcDeviceId }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="opc通道" prop="opcChannelId">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.opcChannelId"
                placeholder="请输入opc通道"
                clearable
              />
              <span v-else>{{ formData.opcChannelId }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.remarks"
                placeholder="请输入备注"
                clearable
              />
              <span v-else>{{ formData.remarks }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="enabled">
              <el-radio-group
                v-if="!props.isReadonly"
                v-model="formData.enabled"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.enabled === 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 照片 -->
        <!-- <el-form-item
        prop="imgUrl"
        style="position: relative; top: -300px; left: 290px"
      >
        <UploadImge
          v-if="show2D3D"
          :action="`${actionUrl}/system/fileCenter/uploadFile/${fileName}`"
          v-model="formData.imgUrl"
          :domainName="`${actionUrl}`"
          :isReadonly="props.isReadonly"
          :uploadStyle="{ width: '150px', height: '150px' }"
          :fileName="fileName"
        ></UploadImge>
        <generaldocument-upload
          v-else
          :multiple="false"
          :showText="false"
          :isRead="props.isReadonly"
          :files="treeImage"
          @update-files="updateFormFiles"
        />
         此input框用于校验功能不显示 -->
        <!-- <el-input v-model="formData.imgUrl" style="display: none"></el-input>
        <div style="position: absolute; top: 160px; left: 15px">
          <el-button @click="show2DImage">2D</el-button>
          <el-button @click="show3DImage">3D</el-button>
        </div>
      </el-form-item> -->

        <div style="position: absolute; top: 0px; right: 40px">
          <UploadImge
            v-if="show2D3D"
            :action="`${actionUrl}/system/fileCenter/uploadFile/${fileName}`"
            v-model="formData.imgUrl"
            :domainName="`${actionUrl}`"
            :isReadonly="props.isReadonly"
            :uploadStyle="{ width: '200px', height: '135px' }"
            :fileName="fileName"
          />
          <scaequinfo-upload
            v-else
            :multiple="false"
            :showText="false"
            :isRead="props.isReadonly"
            :files="treeImage"
            @update-files="updateFormFiles"
          />

          <!-- 此input框用于校验功能不显示 -->
          <el-input v-model="formData.imgUrl" style="display: none" />
          <div style="position: relative; top: 15px; left: 48px">
            <el-button @click="show2DImage">2D</el-button>
            <el-button @click="show3DImage" disabled>3D</el-button>
          </div>
        </div>
      </el-form>

      <div style="text-align: right; margin-top: 20px">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SCAEQUIPINFOCONTENTEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
// 定义上传图片文件夹名
const fileName = ref("scaEquipinfoFile");

// 图片地址
const actionUrl = import.meta.env.VITE_APP_BASE_API;
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      if (formRef.value?.clearValidate) {
        formRef.value && formRef.value.clearValidate();
      }
    }, 50);
  }
);

const rules = reactive({
  version: [],
  equipCode: [
    { required: true, message: "请输入设备编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipName: [
    { required: true, message: "请输入设备名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipModel: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  ipAddress: [
    { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" },
  ],
  equipPort: [
    { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" },
  ],
  imgUrl: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  threeModelUrl: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  equipTypeId: [
    { required: true, message: "请选择设备类型", trigger: "change" },
  ],
  equipStatus: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipStatusName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  locationId: [{ required: true, message: "请选择位置", trigger: "change" }],
  opcDeviceId: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  opcChannelId: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData: any = reactive({
  id: "",
  version: "",
  equipCode: "",
  equipName: "",
  equipModel: "",
  processEquipCode: "",
  processEquipId: "",
  ipAddress: "",
  equipPort: "",
  opcChannelId: "",
  opcDeviceId: "",
  connectionMode: "",
  imgUrl: "",
  threeModelUrl: "",
  equipTypeId: "",
  equipTypeCode: "",
  equipTypeName: "",
  equipStatus: "",
  equipStatusName: "",
  locationId: "",
  locationName: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        equipCode,
        equipName,
        equipModel,
        ipAddress,
        processEquipCode,
        processEquipId,
        equipPort,
        connectionMode,
        opcChannelId,
        opcDeviceId,
        imgUrl,
        threeModelUrl,
        equipTypeId,
        equipTypeCode,
        equipTypeName,
        equipStatus,
        equipStatusName,
        locationId,
        locationName,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        version,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        equipCode,
        equipName,
        equipModel,
        ipAddress,
        equipPort: equipPort ? equipPort.toString() : "",
        processEquipCode,
        processEquipId,
        connectionMode,
        opcChannelId,
        opcDeviceId,
        imgUrl,
        threeModelUrl,
        equipTypeId,
        equipTypeCode,
        equipTypeName,
        equipStatus,
        equipStatusName,
        locationId,
        locationName,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
      treeImage.value.push({
        url: formData.threeModelUrl,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  if (formRef.value?.resetFields) {
    formRef.value.resetFields();
    formRef.value.clearValidate();
  }
  formData.id = "";
  formData.version = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.processEquipCode = "";
  formData.processEquipId = "";
  formData.equipModel = "";
  formData.ipAddress = "";
  formData.equipPort = "";
  formData.imgUrl = "";
  formData.threeModelUrl = "";
  formData.equipTypeId = "";
  formData.equipTypeCode = "";
  formData.equipTypeName = "";
  formData.equipStatus = "";
  formData.equipStatusName = "";
  formData.locationId = "";
  formData.locationName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 设备信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // if (formData.equipPort === "") {
      //   formData.equipPort = null;
      // }
      for (let i = 0; i < equipTypeList.value.length; i++) {
        if (equipTypeList.value[i].value == formData.equipTypeId) {
          formData.equipTypeCode = equipTypeList.value[i].equipTypeCode;
          formData.equipTypeName = equipTypeList.value[i].equipTypeName;
        }
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/iotadmin/scaequipinfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);
const getEquipTypeList = async () => {
  const res = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipTypeList.value = res.data;
    equipTypeList.value?.map((item) => {
      item.label = `${item.equipTypeName}`;
      item.value = `${item.id}`;
    });
  }
};

// 获取设备类型下拉框
const equipProduceList: any = ref([]);
const getEquipProduceList = async () => {
  const res = await request({
    url: "/mdm/mdmequipinfo/getList",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipProduceList.value = res.data;
  }
};

function handleProcessEquip(e: string) {
  if (e) {
    formData.processEquipCode =
      equipProduceList.value.filter((item: any) => item.id === e)[0]
        ?.equipCode || "";
  } else {
    formData.processEquipCode = "";
  }
}

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/mdm/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
// 点击位置树
const handleLocationChange = (e: any, index?: number) => {
  formData.locationId = e.id;
  formData.locationName = e.locationName;
};

onMounted(() => {
  getEquipTypeList();
  getLocationInfoTree();
  getEquipProduceList();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 显示2D 3D
const show2D3D = ref(true);
const show2DImage = () => {
  show2D3D.value = true;
};
const show3DImage = () => {
  show2D3D.value = false;
};

const treeImage: any = ref([]);
// 图片处理
function updateFormFiles(val: []) {
  if (val.length > 0) {
    formData.threeModelUrl = val[0].url;
  } else {
    formData.threeModelUrl = "";
  }
}
</script>
<style lang="scss" scoped>
.dialog-footer {
  margin: -200px 0 0 0;
}

:deep(.el-form-item__content) {
  word-break: break-all;
}

:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 110px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
